import React, { useEffect, useState, useRef } from 'react';
import AutoRenderComponent from '@/pages/WorkFlow/components/FormControls/components/AutoRenderComponent/AutoRenderComponent';
import { Form } from 'antd';
import { getFormatByUnit, getOptionData } from '@/pages/Flow/Mine/ApplyPage/utils';
import { getDuration } from '@/utils/utils';
import moment from 'moment';
import { useRequest } from '@/hooks';
import { dictionaryList, overlong } from './service';

const { Item } = Form;

const Overtime = ({ form, dataSource }) => {
    const { children: list = [] } = dataSource;
    const { getFieldDecorator } = form;
    const [overtimeTypeList, setOvertimeList] = useState([]);
    const user = JSON.parse(localStorage.getItem('user') || {});

    const isChinaArea = user?.areaCode === '86';
    const country = isChinaArea ? 'zh' : 'sg';

    const refForm = useRef(form);

    // 请求时长
    const { data: overlongData, run: runOverlong } = useRequest(params => overlong(params), {
        manual: true
    });

    const fetchTimeCount = async (name, value) => {
        const currentUser = localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')) : {};
        const { firstCompanyCode } = currentUser?.firstOrgInfo;

        const { overTimeType, startTime, endTime } = form.getFieldsValue();
        if (name === 'startTime' && !endTime.time) return;
        if (name === 'endTime' && !startTime.time) return;

        runOverlong({
            companyCode: firstCompanyCode,
            startTime: getFormatByUnit('startTime', country, 3, name === 'startTime' ? value.time : startTime.time),
            endTime: getFormatByUnit('endTime', country, 3, name === 'endTime' ? value.time : endTime.time),
            overType: overTimeType.key
        });
    };

    useEffect(() => {
        if (overlongData) {
            if (overlongData.code === 10000) {
                refForm.current.setFieldsValue({
                    duration: {
                        durationText: getDuration(overlongData.data, 3),
                        duration: overlongData.data
                    }
                });
            } else {
                refForm.current.setFields({
                    duration: {
                        value: 0,
                        errors: [new Error(overlongData.msg)]
                    }
                });
            }
        }
    }, [overlongData]);

    // startTime or endTime change handler
    const handleOnTimeChange = changeValue => {
        const { type } = changeValue;
        form.setFieldsValue({ [type]: changeValue });

        // 计算时长
        if (type === 'startTime') {
            if (form.getFieldValue('endTime')) {
                fetchTimeCount('startTime', changeValue);
            } else {
                form.setFieldsValue({ endTime: undefined });
            }
        }
        // 计算时长
        if (type === 'endTime') {
            if (form.getFieldValue('startTime')) {
                fetchTimeCount('endTime', changeValue);
            } else {
                form.setFieldsValue({ startTime: undefined });
            }
        }
    };

    // 加班类型 change
    const handleOnOvertimeChange = changeValue => {
        form.setFieldsValue({
            overTimeType: changeValue,
            startTime: {
                ...form.getFieldValue('startTime'),
                time: undefined,
                dayType: '',
                disabled: false,
                unit: 3,
                type: 'startTime'
            },
            endTime: {
                ...form.getFieldValue('endTime'),
                time: undefined,
                dayType: '',
                disabled: false,
                unit: 3,
                type: 'endTime'
            },
            duration: ''
        });
        form.validateFields(['startTime', 'endTime'], { force: true });
    };

    // 获取加班类型
    const fetchOvertimeType = async () => {
        // 获取加班类型
        const result = await dictionaryList({
            code: 'overtimeSign'
        });

        if (result.code === 10000) {
            // 前端过滤掉工作日的加班日类型
            let resultData = result.data || [];
            if (country === 'zh') {
                resultData = resultData.filter(item => item.dictValue !== '1');
            }
            const options = getOptionData(resultData, {
                key: 'dictValue',
                label: 'dictName'
            });

            setOvertimeList(options);
        }
    };

    useEffect(() => {
        fetchOvertimeType();
    }, []);

    return (
        Array.isArray(list) &&
        list.map(item => {
            const { label, formId, rules, initialValue, extra } = item;

            if (formId === 'overTimeType') {
                item.dataList = overtimeTypeList;
                item.options = {
                    ...item.options,
                    labelInValue: true,
                    onChange: handleOnOvertimeChange
                };
            }

            if (formId === 'startTime' || formId === 'endTime') {
                item.options = {
                    ...item.options,
                    onChange: handleOnTimeChange
                };

                if (formId === 'startTime') {
                    rules[0] = {
                        ...rules[0],
                        validator(_, value, callback) {
                            const endTime = form.getFieldValue(formId);
                            if (!value || !value.time || (value.unit === 2 && !value.dayType)) {
                                callback('请选择开始时间！');
                            } else if (moment(value.time) > moment(endTime.time)) {
                                callback('开始时间不能晚于结束时间！');
                            } else if (value.time.format('YYYY-MM-DD') !== endTime.time.format('YYYY-MM-DD')) {
                                // 外出、加班不能跨天申请
                                callback('不能跨天申请！');
                            } else {
                                callback();
                            }

                            form.validateFields([formId]);
                        }
                    };
                }

                if (formId === 'endTime') {
                    rules[0] = {
                        ...rules[0],
                        validator(_, value, callback) {
                            const startTime = form.getFieldValue(formId);
                            if (!value || !value.time || (value.unit === 2 && !value.dayType)) {
                                callback('请选择结束时间！');
                            } else if (moment(value.time) < moment(startTime.time)) {
                                callback('结束时间不能早于开始时间！');
                            } else if (value.time.format('YYYY-MM-DD') !== startTime.time.format('YYYY-MM-DD')) {
                                // 外出、加班不能跨天申请
                                callback('不能跨天申请！');
                            } else {
                                callback();
                            }
                            form.validateFields([formId]);
                        }
                    };
                }
            }

            return (
                <Item label={label} key={formId} extra={extra}>
                    {getFieldDecorator(formId, {
                        initialValue,
                        rules
                    })(<AutoRenderComponent form={form} config={item} />)}
                </Item>
            );
        })
    );
};

export default Overtime;
